package install.ren.exercise.test.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * RPC 解码器
 *
 * @author wanglin/netboy
 * @since 1.0.0
 */
public class MessageDecoder extends LengthFieldBasedFrameDecoder {
    Logger log = LoggerFactory.getLogger(MessageDecoder.class);
    private final static int LENGTH_FIELD_OFFSET = 0;
    private final static int LENGTH_FIELD_LENGTH = 4;
    private final static int LENGTH_ADJUSTMENT = -4;
    private final static int INITIAL_BYTES_TO_STRIP = 0;

    public MessageDecoder(int maxFrameLength) {
        this(maxFrameLength, LENGTH_FIELD_OFFSET, LENGTH_FIELD_LENGTH, LENGTH_ADJUSTMENT, INITIAL_BYTES_TO_STRIP);
    }

    public MessageDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment,
                          int initialBytesToStrip) {
        super(maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment, initialBytesToStrip);
    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception {
        Object obj = super.decode(ctx, in);
        Message msg = null;
        if (obj != null && obj instanceof ByteBuf) {
            ByteBuf buf = (ByteBuf) (obj);
            int len = buf.readableBytes();
            if (len > 0) {
                try {
                    msg = MessageBuilder.buildMsg(buf);
                    log.info("sgip received message:{} ", msg);
                } catch (Exception e) {
                    log.error("sgip build msg failed for exception:{}", e.getMessage());
                    throw e;
                } finally {
                    buf.release();
                }
            }
        }
        return msg;
    }
}
